package com.ls.lsojcodesandbox.utils;

import com.ls.lsojcodesandbox.model.ExecuteMessage;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 利用Runtime执行java命令
 */
public class ProcessUtils {

    public static ExecuteMessage runProcessAndGetMessage(Process process, String cmd) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        int exitValue = 0;
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            exitValue = process.waitFor();
            if(exitValue==0) {
                System.out.println(cmd + "成功");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line=bufferedReader.readLine())!=null) {
                    stringBuilder.append(line);
                }
                executeMessage.setMessage(stringBuilder.toString());
            } else {
                System.out.println(cmd + "失败");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line=bufferedReader.readLine())!=null) {
                    stringBuilder.append(line);
                }
                executeMessage.setErrorMessage(stringBuilder.toString());
            }
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setExitValue(exitValue);
        } catch (InterruptedException | IOException e ) {
            throw new RuntimeException(e);
        }
        return executeMessage;
    }
}
